﻿using System;
using System.Data;
using ExampleApplication.DL;
using SQLPXBase.Factory;
using SQLPXBase.Factory.Keys;

namespace ExampleApplication.Models
{
    internal class Articolo:Base.BaseModel
    {
        internal class ArtPK : PrimaryKey
        {
            private int? k1;
            private string k2;
            private string k3;

            private ArtPK()
            {
                k1 = null;
                k2 = null;
                k3 = null;
            }

            public ArtPK(int? k1, string k2, string k3)
            {
                SetValues(new object[] {k1, k2, k3});
            }

            public ArtPK(DataRow rw, params string[] fieldNames) : base(rw, fieldNames)
            {
            }

            public override bool IsEmpty
            {
                get { return !k1.HasValue && string.IsNullOrEmpty(k2) && string.IsNullOrEmpty(k3); }
            }

            public override PrimaryKey DefaultValue
            {
                get { return new ArtPK(); }
            }

            public override object GetSingleValue
            {
                get { return null; }
            }

            public override int KeyLength
            {
                get { return 3; }
            }

            public override object[] GetValues
            {
                get { return IsEmpty ? null : new object[] {k1, k2, k3}; }
            }

            public override void SetValues(object[] values)
            {
                CheckValues(values);

                try
                {
                    int i = 0;
                    k1 = (int?) values[i++];
                    k2 = (string) values[i++];
                    k3= (string) values[i++];
                }
                catch (Exception ex)
                {
                    throw new PrimaryKeyException(ex.Message, ex);
                }


            }
        }

        public string Descrizione { get; set; }

        public Articolo(ModelFactory<sql> factory) : base(factory)
        {
        }

        protected override void Load(PrimaryKey id)
        {
            InitializeFromDB(factory.ProxyManager.GetProxy().Articolo.Load((ArtPK) id));
        }

        protected override void InitializeFromDB(DataRow rw)
        {
            this.SetPK(new ArtPK(rw, "k1", "k2", "k3"));

            Descrizione = rw["descrizione"] as string ?? "";
        }
    }

    internal class ArticoloCollection : Base.ModelCollection<Articolo>
    {
        public class List : IModelCollectionLoader<Articolo, sql>
        {
            public DataTable Load(ModelFactory<sql> factory)
            {
                return factory.ProxyManager.GetProxy().Articolo.List();
            }
        }
    }
}
